import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:web_admin/core/base/base_view_model.dart';
import 'user_list_view_model.dart';
import 'user_form.dart';
import 'user_model.dart';

mixin UserListViewMixin {
  void showUserForm(BuildContext context, {UserModel? user}) {
    showDialog(
      context: context,
      builder: (dialogContext) => Dialog(
        child: ChangeNotifierProvider.value(
          value: context.read<UserListViewModel>(),
          child: Container(
            padding: const EdgeInsets.all(16),
            constraints: const BoxConstraints(maxWidth: 600),
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    user == null ? '创建用户' : '编辑用户',
                    style: Theme.of(dialogContext).textTheme.titleLarge,
                  ),
                  const SizedBox(height: 16),
                  Builder(
                    builder: (builderContext) => UserForm(
                      user: user,
                      onSubmit: (userData) async {
                        try {
                          final viewModel = builderContext.read<UserListViewModel>();
                          if (user == null) {
                            await viewModel.createUser(userData);
                            if (builderContext.mounted) {
                              Navigator.of(dialogContext).pop();
                              ScaffoldMessenger.of(builderContext).showSnackBar(
                                const SnackBar(content: Text('用户创建成功')),
                              );
                            }
                          } else {
                            await viewModel.updateUser(user.id, userData);
                            if (builderContext.mounted) {
                              Navigator.of(dialogContext).pop();
                              ScaffoldMessenger.of(builderContext).showSnackBar(
                                const SnackBar(content: Text('用户更新成功')),
                              );
                            }
                          }
                          // 刷新用户列表
                          viewModel.fetchUsers();
                        } catch (e) {
                          if (builderContext.mounted) {
                            ScaffoldMessenger.of(builderContext).showSnackBar(
                              SnackBar(content: Text('操作失败: ${e.toString()}')),
                            );
                          }
                        }
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  void updateUser(BuildContext context, UserModel user, Map<String, dynamic> data) async {
    try {
      final viewModel = context.read<UserListViewModel>();
      await viewModel.updateUser(user.id, data);
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('用户状态更新成功')),
        );
      }
      // 刷新用户列表
      viewModel.fetchUsers();
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('更新失败: ${e.toString()}')),
        );
      }
    }
  }

  void showDeleteConfirmDialog(BuildContext context, UserModel user) {
    showDialog(
      context: context,
      builder: (dialogContext) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除用户 ${user.username} 吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(dialogContext).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              try {
                final viewModel = context.read<UserListViewModel>();
                await viewModel.deleteUser(user.id);
                Navigator.of(dialogContext).pop();
                if (context.mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('用户删除成功')),
                  );
                }
                // 刷新用户列表
                viewModel.fetchUsers();
              } catch (e) {
                if (context.mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('删除失败: ${e.toString()}')),
                  );
                }
              }
            },
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }
}

class UserListView extends StatelessWidget {
  const UserListView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) {
        final viewModel = UserListViewModel();
        // 初始化时加载用户列表
        WidgetsBinding.instance.addPostFrameCallback((_) {
          viewModel.fetchUsers();
        });
        return viewModel;
      },
      child: Builder(
        builder: (context) => const _UserListViewContent(),
      ),
    );
  }
}

class _UserListViewContent extends StatelessWidget with UserListViewMixin {
  const _UserListViewContent({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('用户管理'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          showUserForm(context);
        },
        child: const Icon(Icons.add),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // 搜索栏
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        decoration: const InputDecoration(
                          hintText: '搜索用户...',
                          prefixIcon: Icon(Icons.search),
                          border: OutlineInputBorder(),
                        ),
                        onChanged: (value) {
                          context.read<UserListViewModel>().searchUsers(value);
                        },
                      ),
                    ),
                    const SizedBox(width: 16),
                    // 排序按钮
                    PopupMenuButton<String>(
                      icon: const Icon(Icons.sort),
                      onSelected: (value) {
                        context.read<UserListViewModel>().sortUsers(value);
                      },
                      itemBuilder: (context) => [
                        const PopupMenuItem(
                          value: 'username_asc',
                          child: Text('用户名升序'),
                        ),
                        const PopupMenuItem(
                          value: 'username_desc',
                          child: Text('用户名降序'),
                        ),
                        const PopupMenuItem(
                          value: 'created_at_desc',
                          child: Text('创建时间降序'),
                        ),
                        const PopupMenuItem(
                          value: 'created_at_asc',
                          child: Text('创建时间升序'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            
            // 用户列表
            Expanded(
              child: Consumer<UserListViewModel>(
                builder: (context, viewModel, _) {
                  if (viewModel.isBusy) {
                    return const Center(child: CircularProgressIndicator());
                  }

                  if (viewModel.state == ViewState.error) {
                    return Center(
                      child: Text(
                        viewModel.errorMessage ?? '加载失败',
                        style: const TextStyle(color: Colors.red),
                      ),
                    );
                  }

                  final users = viewModel.filteredUsers;
                  if (users.isEmpty) {
                    return const Center(child: Text('暂无用户数据'));
                  }

                  return Card(
                    child: Column(
                      children: [
                        // 表头
                        Container(
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            border: Border(
                              bottom: BorderSide(
                                color: Theme.of(context).dividerColor,
                              ),
                            ),
                          ),
                          child: Row(
                            children: const [
                              Expanded(flex: 2, child: Text('用户信息')),
                              Expanded(flex: 2, child: Text('联系方式')),
                              Expanded(flex: 2, child: Text('角色')),
                              Expanded(flex: 1, child: Text('状态')),
                              Expanded(flex: 1, child: Text('操作')),
                            ],
                          ),
                        ),
                        
                        // 用户列表
                        Expanded(
                          child: ListView.builder(
                            itemCount: users.length,
                            itemBuilder: (context, index) {
                              final user = users[index];
                              return Container(
                                padding: const EdgeInsets.all(16),
                                decoration: BoxDecoration(
                                  border: Border(
                                    bottom: BorderSide(
                                      color: Theme.of(context).dividerColor,
                                    ),
                                  ),
                                ),
                                child: Row(
                                  children: [
                                    // 用户信息
                                    Expanded(
                                      flex: 2,
                                      child: Row(
                                        children: [
                                          CircleAvatar(
                                            backgroundImage: user.avatar != null
                                                ? NetworkImage(user.avatar!)
                                                : null,
                                            child: user.avatar == null
                                                ? Text(user.username[0].toUpperCase())
                                                : null,
                                          ),
                                          const SizedBox(width: 12),
                                          Expanded(
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                  user.username,
                                                  style: const TextStyle(
                                                    fontWeight: FontWeight.bold,
                                                  ),
                                                ),
                                                Text(
                                                  user.nickname,
                                                  style: TextStyle(
                                                    color: Theme.of(context).textTheme.bodySmall?.color,
                                                  ),
                                                ),
                                                if (user.lastLoginAt != null)
                                                  Text(
                                                    '最后登录: ${_formatDateTime(user.lastLoginAt!)}',
                                                    style: TextStyle(
                                                      color: Theme.of(context).textTheme.bodySmall?.color,
                                                      fontSize: 12,
                                                    ),
                                                  ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    
                                    // 联系方式
                                    Expanded(
                                      flex: 2,
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(user.email),
                                          if (user.phone != null) Text(user.phone!),
                                          if (user.lastLoginIP != null)
                                            Text(
                                              'IP: ${user.lastLoginIP}',
                                              style: TextStyle(
                                                color: Theme.of(context).textTheme.bodySmall?.color,
                                                fontSize: 12,
                                              ),
                                            ),
                                        ],
                                      ),
                                    ),
                                    
                                    // 角色
                                    Expanded(
                                      flex: 2,
                                      child: Wrap(
                                        spacing: 4,
                                        children: user.roles.map((role) {
                                          return Chip(
                                            label: Text(
                                              role.name,
                                              style: const TextStyle(fontSize: 12),
                                            ),
                                          );
                                        }).toList(),
                                      ),
                                    ),
                                    
                                    // 状态
                                    Expanded(
                                      flex: 1,
                                      child: Switch(
                                        value: user.isActive,
                                        onChanged: (value) {
                                          updateUser(context, user, {'is_active': value});
                                        },
                                      ),
                                    ),
                                    
                                    // 操作
                                    Expanded(
                                      flex: 1,
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.end,
                                        children: [
                                          IconButton(
                                            icon: const Icon(Icons.edit),
                                            onPressed: () {
                                              showUserForm(context, user: user);
                                            },
                                          ),
                                          IconButton(
                                            icon: const Icon(Icons.delete),
                                            onPressed: () {
                                              showDeleteConfirmDialog(context, user);
                                            },
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            },
                          ),
                        ),
                        
                        // 分页
                        Container(
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            border: Border(
                              top: BorderSide(
                                color: Theme.of(context).dividerColor,
                              ),
                            ),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text('共 ${viewModel.totalItems} 条记录'),
                              Row(
                                children: [
                                  TextButton(
                                    onPressed: viewModel.currentPage > 1
                                        ? () => viewModel.previousPage()
                                        : null,
                                    child: const Text('上一页'),
                                  ),
                                  Text('第 ${viewModel.currentPage} 页'),
                                  TextButton(
                                    onPressed: viewModel.hasNextPage
                                        ? () => viewModel.nextPage()
                                        : null,
                                    child: const Text('下一页'),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _formatDateTime(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} '
        '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }
}